package cn.ictgu.dao.service;

import cn.ictgu.dto.VideoInfo;
import cn.ictgu.dao.mapper.LiveMapper;
import cn.ictgu.dao.model.Live;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 直播视频流 服务层
 * Created by Silence on 2016/12/5.
 */
@Service
public class LiveService {
  private final static int TIMEOUT = 60000;
  private final static String CCTV_REGX = "\"flv4\":\"(.*?)\"";

  @Autowired
  private LiveMapper liveMapper;

  public VideoInfo getVideo(String sname){
    VideoInfo videoInfo = new VideoInfo();
    Live live = liveMapper.selectByName(sname);
    String name = live.getName();
    String value = live.getValue();
    String type = live.getType();
    String iamge = live.getImage();
    switch (type){
      case "CCTV":
        videoInfo = this.parseCCTV(name, iamge, value);
        break;
      case "LETV":
        videoInfo = this.parseLetv(name, iamge, value);
        break;
      default:
        break;
    }
    return videoInfo;
  }

  private VideoInfo parseCCTV(String name, String image, String value){
    VideoInfo videoInfo = new VideoInfo();
    videoInfo.setTitle(name);
    String html = this.html(value);
    Matcher matcher = Pattern.compile(CCTV_REGX).matcher(html);
    if (matcher.find()){
      String playUrl = matcher.group(1);
      videoInfo.setPlayUrl(playUrl);
    }
    return videoInfo;
  }

  private VideoInfo parseLetv(String name, String image, String value){
    VideoInfo videoInfo = new VideoInfo();
    videoInfo.setTitle(name);
    JSONObject object = this.jsonFromDoucment(value);
    String playUrl = object.getString("location");
    videoInfo.setPlayUrl(playUrl);
    return videoInfo;
  }

  private Document htmlDocument(String url){
    Document document = null;
    try {
      document = Jsoup.connect(url).timeout(TIMEOUT).ignoreContentType(true).get();
    } catch (IOException e) {

      e.printStackTrace();
    }
    return document;
  }

  private String html(String url){
    Document document = this.htmlDocument(url);
    return document.html();
  }

  private JSONObject jsonFromDoucment(String url){
    Document document = this.htmlDocument(url);
    String text = document.body().text();
    return JSONObject.parseObject(text);
  }

}
